package hot100.logos41To50;

import hot100.datastruct.TreeNode;

/**
 * @author logos
 * date 2025/7/14 12:11
 * @version v1.0
 * @Package hot100.logos41To50
 */
public class logos44 {

    /**
     * 44. 二叉搜索树中第k小的元素
     * https://leetcode.cn/problems/kth-smallest-element-in-a-bst/description/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        private int ans;

        private int k;

        public int kthSmallest(TreeNode root, int k) {
            this.k = k;
            dfs(root);
            return ans;
        }

        private void dfs(TreeNode root) {
            if (root == null || k == 0) {
                return;
            }
            dfs(root.left);
            if (--k == 0) {
                ans = root.val;
            }
            dfs(root.right);
        }
    }
}
